package cn.kilo.domain.support;

import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.h5.H5Service;
import com.wechat.pay.java.service.payments.h5.model.*;
import com.wechat.pay.java.service.payments.model.Transaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author kilok
 */
@Slf4j
@Component
public class WeChatSupport {
    //"D:/key/apiclient_key.pem"  /home/jar/key/apiclient_key.pem
    public static Config config= new RSAAutoCertificateConfig.Builder()
            .merchantId("1677148696")
            .privateKeyFromPath("D:/key/apiclient_key.pem")
            .merchantSerialNumber("1204C31EC5F3E4248253BB2FC7D5D548AA3BDE9B")
            .apiV3Key("7TYWfF5idjRMzGkqNNbhIwbJnZABXzqa")
            .build();

    /**
     * 预下单
     * 商户系统先调用该接口在微信支付服务后台生成预支付交易单，
     * 返回正确的预支付交易会话标识后再按Native、JSAPI、APP等不同场景生成交易串调起支付。
     */
    public String prePay(String orderNo,Integer price,String ip) {
        log.info("构建预支付订单");
        //构建service
        H5Service h5Service=new H5Service.Builder().config(config).build();

        PrepayRequest prepayRequest=new PrepayRequest();

        Amount amount=new Amount();
        H5Info h5Info=new H5Info();
        h5Info.setType("场景类型");
        SceneInfo sceneInfo=new SceneInfo();
        sceneInfo.setPayerClientIp(ip);
        sceneInfo.setH5Info(h5Info);

        //设置金额(单位：分)
        amount.setTotal(price);
        prepayRequest.setAmount(amount);
        prepayRequest.setAppid("wx71df0eacad878acf");
        prepayRequest.setMchid("1677148696");
        prepayRequest.setOutTradeNo(orderNo);
        prepayRequest.setDescription("商品描述");
        prepayRequest.setNotifyUrl("http://nefuexpress.com:8091/wx/callBack");
        prepayRequest.setSceneInfo(sceneInfo);
        PrepayResponse prepay = h5Service.prepay(prepayRequest);
        log.info("支付url:{}",prepay.getH5Url());
        //应答参数为支付跳转链接，h5_url为拉起微信支付收银台的中间页面，可通过访问该URL来拉起微信客户端，完成支付，h5_url的有效期为5分钟。
        return prepay.getH5Url();
    }

    public void closeOrder(String orderId,String mchId){
        H5Service h5Service=new H5Service.Builder().config(config).build();
        CloseOrderRequest closeOrderRequest=new CloseOrderRequest();
        closeOrderRequest.setOutTradeNo(orderId);
        closeOrderRequest.setMchid(mchId);
        h5Service.closeOrder(closeOrderRequest);
    }

    public Transaction getOrderInfo(String orderId, String mchId){
        H5Service h5Service=new H5Service.Builder().config(config).build();
        QueryOrderByOutTradeNoRequest request=new QueryOrderByOutTradeNoRequest();
        request.setMchid(mchId);
        request.setOutTradeNo(orderId);
        return  h5Service.queryOrderByOutTradeNo(request);
    }

}
